<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button
                  v-hasPerm="['configgroup@add']"
                  @click="openDialog(undefined, 'type-form')"
                  type="success"
                  ><i-ep-plus />新增</el-button
                >
              </div>
              <div>
                <el-button
                  class="ml-3"
                  title="刷新"
                  @click="handleQuery"
                  icon="Refresh"
                  circle
                />
              </div>
            </div>
          </template>
          <el-table
            ref="singleTable"
            v-loading="loading"
            :data="dictType"
            fit
            @row-click="dictTypeChange"
            style="width: 100%"
          >
            <el-table-column label="分组名称" align="center">
              <template #default="scope">
                <span class="link-type">{{ scope.row.title }}</span
                >&nbsp;&nbsp;
                <el-icon size="10" v-if="currentRowId == scope.row.id"
                  ><DArrowRight
                /></el-icon>
              </template>
            </el-table-column>

            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="95"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  size="small"
                  v-hasPerm="['configgroup@edit']"
                  title="编辑"
                  type="primary"
                  @click="openDialog(scope.row.id, 'type-form')"
                  circle
                  icon="edit"
                />
                <el-button
                  size="small"
                  v-hasPerm="['configgroup@del']"
                  title="删除"
                  icon="delete"
                  @click="handleTypeDelete(scope.row.id)"
                  circle
                  type="danger"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button
                  v-hasPerm="['config@add']"
                  @click="openDialog(undefined, 'dict-form')"
                  type="success"
                  ><i-ep-plus />新增</el-button
                >
                <el-button
                  v-if="removeIds.length > 0"
                  v-hasPerm="['config@del']"
                  type="danger"
                  @click="handleDictDelete()"
                  ><i-ep-delete />删除</el-button
                >
              </div>
              <div>
                <div v-if="isShowSearchBtn" style="display: inline-block">
                  <el-form
                    ref="queryFormRef"
                    :model="queryParams"
                    :inline="true"
                  >
                    <el-form-item label="关键字" prop="title">
                      <el-input
                        v-model="queryParams.title"
                        placeholder="名称/编码"
                        clearable
                        style="width: 200px"
                        @keyup.enter="handleDictQuery"
                      />
                    </el-form-item>

                    <el-form-item label="状态" prop="is_hid">
                      <el-select
                        v-model="queryParams.is_hid"
                        placeholder="全部"
                        clearable
                        class="!w-[100px]"
                      >
                        <el-option label="启用" value="0" />
                        <el-option label="禁用" value="1" />
                      </el-select>
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" @click="handleDictQuery"
                        ><i-ep-search />搜索</el-button
                      >
                      <el-button @click="resetQuery">
                        <i-ep-refresh />
                        重置</el-button
                      >
                    </el-form-item>
                  </el-form>
                </div>
                <el-button
                  class="ml-3"
                  icon="Search"
                  circle
                  @click="handleSearchShowBtn"
                />
                <el-button
                  class="ml-3"
                  title="刷新"
                  @click="handleDictQuery"
                  icon="Refresh"
                  circle
                />
              </div>
            </div>
          </template>
          <el-table
            v-loading="loadingData"
            :data="pageData"
            fit
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column align="center" type="selection" />
            <!--
            <el-table-column label="字典名称" align="left">
              <template #default="scope">
                <span class="link-type">{{ scope.row.title }}</span>
              </template>
            </el-table-column>
			-->
            <el-table-column label="字典编码" align="left">
              <template #default="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="字典值" align="center">
              <template #default="scope">
                <span class="overflow">{{ scope.row.value }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-tag
                  effect="dark"
                  :type="scope.row.is_hid == 0 ? 'success' : 'danger'"
                  >{{ scope.row.is_hid == 0 ? "启用" : "禁用" }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="排序" align="center">
              <template #default="scope">
                <span>{{ scope.row.sort }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" width="160">
              <template #default="scope">
                <span>{{ scope.row.created_at }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  v-hasPerm="['config@edit']"
                  @click="openDialog(scope.row.id, 'dict-form')"
                  title="编辑"
                  type="primary"
                  icon="edit"
                  circle
                />
                <el-button
                  v-hasPerm="['config@del']"
                  title="删除"
                  @click="handleDictDelete(scope.row.id)"
                  icon="delete"
                  circle
                  type="danger"
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.p"
            v-model:limit="queryParams.limit"
            @pagination="handleDictQuery"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 字典类型新增/编辑表单 -->
      <el-form
        v-if="dialog.type == 'type-form'"
        ref="dictTypeFormRef"
        :model="dictTypeFormData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item style="margin-bottom: 18px" label="字典名称" prop="title">
          <el-input
            v-model="dictTypeFormData.title"
            :readonly="!!dictTypeFormData.id"
            placeholder="请输入字典名称"
          />
        </el-form-item>
        <el-form-item
          style="margin-bottom: 18px"
          label="字典编码"
          prop="table_name"
        >
          <el-input
            v-model="dictTypeFormData.table_name"
            placeholder="请输入字典编码"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="排序" prop="sort">
          <el-input-number
            v-model="dictTypeFormData.sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="状态" prop="is_hid">
          <el-radio-group v-model="dictTypeFormData.is_hid">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 字典新增/编辑表单 -->
      <el-form
        v-if="dialog.type == 'dict-form'"
        ref="dictFormRef"
        :model="dictFormData"
        :rules="dictRules"
        label-width="80px"
      >
        <!--
        <el-form-item style="margin-bottom:18px;" label="字典名称" prop="title">
          <el-input
            v-model="dictFormData.title"
            :readonly="!!dictFormData.id"
            placeholder="请输入字典名称"
          />
        </el-form-item>
		-->
        <el-form-item style="margin-bottom: 18px" label="字典编码" prop="name">
          <el-input v-model="dictFormData.name" placeholder="请输入字典编码" />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="字典值" prop="value">
          <el-input v-model="dictFormData.value" placeholder="请输入字典值" />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="排序" prop="sort">
          <el-input-number
            v-model="dictFormData.sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="状态" prop="is_hid">
          <el-radio-group v-model="dictFormData.is_hid">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getDictTypePage,
  getDictPage,
  delDictType,
  dictTypeForm,
  delDict,
  dictForm,
  dictUpdate,
  dictCreate,
  dictTypeUpdate,
  dictTypeCreate,
} from "@/api/dict";
import {
  DictTypePageVO,
  DictQuery,
  DictPageVO,
  DictTypeForm,
  DictForm,
} from "@/api/dict/types";

const loading = ref(false);
const loadingData = ref(false);
const dictType = ref<DictTypePageVO[]>();
const pageData = ref<DictPageVO[]>();
const currentRowId = ref(undefined);
const total = ref(0);
const removeIds = ref([]);
const queryFormRef = ref(ElForm); // 查询表单
const queryParams = reactive<DictQuery>({
  p: 1,
  limit: 10,
});
const dictTypeFormRef = ref(ElForm); // 用户表单
const dictFormRef = ref(ElForm); // 用户表单
const dialog = reactive({
  visible: false,
  type: "type-form",
  width: 800,
  title: "",
});
const dictTypeFormData = reactive<DictTypeForm>({
  is_hid: 0,
  sort: 0,
});

const dictFormData = reactive<DictForm>({
  is_hid: 0,
  sort: 0,
});

const rules = reactive({
  title: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
  table_name: [
    { required: true, message: "字典编码不能为空", trigger: "blur" },
  ],
});

const dictRules = reactive({
  //title: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
  name: [{ required: true, message: "字典编码不能为空", trigger: "blur" }],
  value: [{ required: true, message: "字典编码不能为空", trigger: "blur" }],
});
const isShowSearchBtn = ref(false);

//字典类型查询
function handleQuery() {
  loading.value = true;
  getDictTypePage()
    .then(({ data }) => {
      if (data.length > 0) {
        dictType.value = data;
        queryParams.table_name = data[0].table_name;
        currentRowId.value = data[0].id;
        handleDictQuery();
      }
    })
    .finally(() => {
      loading.value = false;
    });
}
//字典查询
function handleDictQuery() {
  loadingData.value = true;
  getDictPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loadingData.value = false;
    });
}

function dictTypeChange(row: any, column: any, event: Event) {
  queryParams.table_name = row.table_name;
  currentRowId.value = row.id;
  handleDictQuery();
}

//删除
function handleTypeDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    delDictType({ ids: ids }).then(() => {
      handleQuery();
      ElMessage.success("删除成功");
    });
  });
}

function handleDictDelete(id?: number) {
  const ids = id || removeIds.value;
  console.log(ids);
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    delDict({ ids: ids }).then(() => {
      handleDictQuery();
      ElMessage.success("删除成功");
    });
  });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleDictQuery();
}

/**
 * 打开弹窗
 * @param id 用户ID
 */
async function openDialog(id?: number, type?: string) {
  dialog.visible = true;
  if (type) {
    dialog.type = type;
  }
  if (id) {
    dialog.title = "修改";
    if (type == "dict-form") {
      dictForm(id).then(({ data }) => {
        Object.assign(dictFormData, { ...data });
      });
    } else {
      dictTypeForm(id).then(({ data }) => {
        Object.assign(dictTypeFormData, { ...data });
      });
    }
  } else {
    dialog.title = "新增";
  }
}

const handleSubmit = useThrottleFn(() => {
  if (dialog.type == "type-form") {
    dictTypeFormRef.value.validate((valid: any) => {
      if (valid) {
        const ids = dictTypeFormData.id;
        loading.value = true;
        if (ids) {
          dictTypeUpdate(dictTypeFormData)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          dictTypeCreate(dictTypeFormData)
            .then(() => {
              ElMessage.success("新增成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  } else {
    dictFormRef.value.validate((valid: any) => {
      if (valid) {
        const ids = dictFormData.id;
        dictFormData.group_name = queryParams.table_name;
        loading.value = true;
        if (ids) {
          dictUpdate(dictFormData)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
            })
            .finally(() => (loading.value = false));
        } else {
          dictCreate(dictFormData)
            .then(() => {
              ElMessage.success("新增成功");
              closeDialog();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
}, 3000);

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type == "type-form") {
    dictTypeFormRef.value.resetFields();
    dictTypeFormRef.value.clearValidate();
    dictTypeFormData.id = undefined;
    handleQuery();
  } else {
    dictFormRef.value.resetFields();
    dictFormRef.value.clearValidate();
    dictFormData.id = undefined;
    handleDictQuery();
  }
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.overflow {
  width: 220px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
.el-form-item {
  margin-bottom: 0;
}
</style>
